#pragma once
#include "Socket.hpp"
#include <string>
#include <memory>
#include <jsoncpp/json/json.h>
#include <functional>

using namespace MySocket;

class Request
{
public:
    Request() {}
    Request(int x, int y, char oper) : _x(x), _y(y), _oper(oper)
    {
    }

    // 反序列化
    bool DeSerialize(std::string &in)
    {
        Json::Value root;
        Json::Reader reader;

        bool ok = reader.parse(in, root);
        if (ok)
        {
            _x = root["x"].asInt();
            _y = root["y"].asInt();
            _oper = root["oper"].asInt();
        }
        return ok;
    }

    ~Request()
    {
    }

    const int X() { return _x; }
    const int Y() { return _y; }
    const char Oper() { return _oper; }

private:
    int _x;
    int _y;
    char _oper;
};

class Response
{
public:
    Response() {}
    Response(int result, int code)
        : _result(result), _code(code)
    {
    }
    std::string Serialize()
    {
        Json::Value root;
        Json::FastWriter writer;

        root["result"] = _result;
        root["code"] = _code;
        return writer.write(root);
    }

    void ShowResult()
    {
        std::cout<<"计算结果为: "<<_result<<"["<<_code<<"]"<<std::endl;
    }
    ~Response()
    {
    }
    void SetRes(int res) { _result = res; }
    void SetCode(int code) { _code = code; }

private:
    int _result;
    int _code;
};

const std::string sep = "\r\n";
using func_t = std::function<Response (Request& req)>;

class Potorol
{
public:
    Potorol(){}
    Potorol(func_t func):_func(func)
    {}

    std::string Encode(const std::string &jsonstr)
    {
        std::string len = std::to_string(jsonstr.size());
        return len + sep + jsonstr + sep;
    }

    bool Decode(std::string& buffer,std::string *package)
    {
        ssize_t pos = buffer.find(sep);
        if(pos == std::string::npos)
            return false;
        
        std::string package_len_str = buffer.substr(0,pos);
        int package_len_int = std::stoi(package_len_str);

        int target_len = package_len_str.size() + package_len_int + 2*sep.size();
        if(buffer.size()<target_len)
            return false;
        
        *package = buffer.substr(pos+sep.size(),package_len_int);
        buffer.erase(0,target_len);
        return true;
    }

    std::string Excute(std::string &package)
    {
        Request req;
        bool ok = req.DeSerialize(package);
        if(!ok)
            return std::string();

        Response resp = _func(req);

        std::string json_str = resp.Serialize();

        std::string send_str = Encode(json_str);

        return send_str;
    }

    ~Potorol() {}

private:
    //回调函数
    func_t _func;
    // Request _req;
    // Response _res;
};